import axios from 'axios'
import { Message } from 'view-design'
import store from '../store'
import { getToken } from '@/libs/util'
// import {baseUrl} from '@/config/env'
import config from '@/config'

const baseUrl = process.env.NODE_ENV === 'development' ? config.baseUrl.dev : config.baseUrl.pro
// 创建axios实例
const service = axios.create({
  baseURL: baseUrl, // api的base_url
  timeout: 5000 // 请求超时时间
})

// request拦截器
service.interceptors.request.use(config => {
  if (getToken()) {
    config.headers['authorization'] = 'Bearer ' + getToken() // 让每个请求携带自定义token 请根据实际情况自行修改
  }
  // config.headers.post['Content-Type'] = 'application/json;charset=UTF-8'
  config.headers.post['Content-Type'] = 'application/json; charset=utf-8'
  config.headers.put['Content-Type'] = 'application/json; charset=utf-8'
  return config
},
error => {
  console.log(error) // for debug
  Promise.reject(error)
}
)

// respone拦截器
service.interceptors.response.use(
  response => {
    const res = response.data
    return res
    // TODO
    if (res.code !== 0) {
      Message.error({
        content: res.message,
        duration: 2
      })
      // 50008:非法的token; 50012:其他客户端登录了;  50014:Token 过期了;
      if (res.code === 50008 || res.code === 50012 || res.code === 50014) {
        MessageBox.confirm('你已被登出，可以取消继续留在该页面，或者重新登录', '确定登出', {
          confirmButtonText: '重新登录',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          store.dispatch('FedLogOut').then(() => {
            location.reload()// 为了重新实例化vue-router对象 避免bug
          })
        })
      }
      return Promise.reject('error')
    } else {
      return response.data
    }
  },
  error => {
    console.log('err' + error)// for debug
    Message.error({
      content: error.message,
      duration: 2
    })
    return Promise.reject(error)
  }
)

/**
 * 封装get方法
 * @param url
 * @param data
 * @returns {Promise}
 */
const fetch = (url, params = {}) => {
  return new Promise((resolve, reject) => {
    service.get(url, {
      params: params
    })
      .then(response => {
        resolve(response)
      })
      .catch(err => {
        reject(err)
      })
  })
}

/**
 * 封装post请求
 * @param url
 * @param data
 * @returns {Promise}
 */
const post = (url, data = {}) => {
  return new Promise((resolve, reject) => {
    service.post(url, data)
      .then(response => {
        resolve(response)
      }, err => {
        reject(err)
      })
  })
}

/**
 * 封装delete请求
 * @param url
 * @param data
 * @returns {Promise}
 */
const del = (url, data = {}) => {
  return new Promise((resolve, reject) => {
    service.delete(url, { data: data })
      .then(response => {
        resolve(response)
      }, err => {
        reject(err)
      })
  })
}

/**
 * 封装patch请求
 * @param url
 * @param data
 * @returns {Promise}
 */
const patch = (url, data = {}) => {
  return new Promise((resolve, reject) => {
    service.patch(url, data)
      .then(response => {
        resolve(response)
      }, err => {
        reject(err)
      })
  })
}

/**
 * 封装put请求
 * @param url
 * @param data
 * @returns {Promise}
 */
const put = (url, data = {}) => {
  return new Promise((resolve, reject) => {
    service.put(url, data)
      .then(response => {
        resolve(response)
      }, err => {
        reject(err)
      })
  })
}

/**
 *  文件上传
 *  url:请求地址
 *  params:参数
 */
const fileUpload = (url, params = {}) => {
  return new Promise((resolve, reject) => {
    service({
      url: url,
      method: 'post',
      data: params,
      headers: { 'Content-Type': 'multipart/form-data' }
    }).then(response => {
      resolve(response)
    }).catch(error => {
      reject(error)
    })
  })
}

export default {
  service, fetch, post, del, patch, put, fileUpload
}
